package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path"
	"project1/models"
	"strconv"
)

type UserController struct{}

func (con UserController) Index(c *gin.Context) {
	c.String(200, "人员管理首页")
}

func (con UserController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/useradd.html", gin.H{})
}

func (con UserController) Upload(c *gin.Context) {
	username := c.PostForm("username")
	file, err := c.FormFile("face")

	if err == nil {
		extName := path.Ext(file.Filename)
		allowExtMap := map[string]bool{
			".png":  true,
			".jpg":  true,
			".jpeg": true,
		}
		if _, ok := allowExtMap[extName]; !ok {
			c.String(200, "传入文件格式不合法")
			return
		}
		day := models.GetDay()
		dir := "./static/upload/" + day
		err := os.MkdirAll(dir, 0666)
		if err != nil {
			c.String(200, "Mkdir失败")
			return
		}

		fileName := strconv.FormatInt(models.GetUnix(), 10) + extName

		//相对地址是相对于main.go的，因为这些函数最后都会引入到main.go中使用
		dst := path.Join(dir, fileName)
		c.SaveUploadedFile(file, dst)
	}
	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"username": username,
	})
}

func (u UserController) Edit(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/useredit.html", gin.H{})
}

func (u UserController) UploadMany(c *gin.Context) {
	username := c.PostForm("username")
	file1, err := c.FormFile("face1")
	//相对地址是相对于main.go的，因为这些函数最后都会引入到main.go中使用
	if err == nil {
		dst := path.Join("./static/upload", file1.Filename)
		c.SaveUploadedFile(file1, dst)
	}
	file2, err := c.FormFile("face2")
	//相对地址是相对于main.go的，因为这些函数最后都会引入到main.go中使用
	if err == nil {
		dst := path.Join("./static/upload", file2.Filename)
		c.SaveUploadedFile(file2, dst)
	}
	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"username": username,
	})
}

func (u UserController) MultiUpload(c *gin.Context) {
	username := c.PostForm("username")
	form, _ := c.MultipartForm()
	files := form.File["face"]
	for _, file := range files {
		dst := path.Join("./static/upload", file.Filename)
		c.SaveUploadedFile(file, dst)
	}

	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"username": username,
	})
}
